import { makeAutoObservable, observable } from 'mobx';
import * as api from './api';

export default class RefundStore {
  _args = {
    search: {
    },
    pg: {
      page: 0,
      sort: this._orderStatus === '0' ? ['refundInfo.refundTime;DESC'] : ['upDate;DESC'],
      size: 10,
    },
  };
  total = 0;
  refund = [];
  loading = false;
  _orderStatus = '1'; // '1';

  constructor(rootStore) {
    this.rootStore = rootStore;
    makeAutoObservable(this, { rootStore: false });
  }

  /**
   * 使用设置的请求参数和分页配置请求列表数据
   * 分页参数为空时保持当前分页配置
   * @param {object} pgInfo 分页参数
   */
  * query(pgInfo) {
    _.mergeWith(this._args.pg, pgInfo, (o, s) => (_.isArray(o) ? s : undefined)); // 数组直接赋值，不合并
    const { search, pg } = toJS(this._args);
    search.orderType = Number(this._orderStatus) + 1;
    if (!pg.sort?.length) delete pg.sort;
    this.loading = true;
    try {
      this.total = yield api.getApplicationsCount({ search });
      this.refund = yield api.getApplications({ search, pg });
    } finally {
      this.loading = false;
    }
  }

  * get(id) {
    const res = yield api.get(id);
    return observable(res);
  }

  * getIdRefund(id) {
    const res = yield api.getIdRefund(id);
    return observable(res);
  }

  * getRefund(id) {
    const res = yield api.getRefund(id);
    return observable(res);
  }

  idx(i) {
    return this._args.pg.page * this._args.pg.size + i + 1;
  }

  get pg() {
    return this._args.pg;
  }

  set pg(pg) {
    this.query({ ...pg });
  }

  get orderStatus() {
    return this._orderStatus;
  }

  set orderStatus(value) {
    this._orderStatus = value;
    this._args.pg.page = 0;
    this.query({ page: 0 });
  }

  // 退款
  * onRefund(refund) {
    yield api.onRefund(refund);
    yield this.query();
  }

  // 驳回
  * onReject(refund) {
    yield api.onReject(refund);
    yield this.query();
  }

  get search() {
    this._args.pg.page = 0;
    return this._args.search;
  }

  set search(search) {
    this._args.pg.page = 0;
    this._args.search = search;
    this.query({ page: 0 });
  }

  get tableSort() {
    if (this._args.pg.sort?.length) {
      const [fn, dir] = this._args.pg.sort[0].split(';');
      return { [fn]: dir };
    }
    return undefined;
  }
}
